import {PageContainer} from '@ant-design/pro-components';

import React, {useEffect, useState, useRef} from 'react';

import {
  Descriptions,
  Avatar,
  Card,
  message,
  Divider,
  Button,
  Space,
  Form,
  Input,
  Upload,
  Alert,
  Row,
  Col,
  UploadProps, UploadFile
} from "antd"
import {
  getLoginUserUsingGet,
  refreshAccessKeyUsingPost,
  updateUserUsingPost
} from "@/services/api-backend/userController";
import styles from './index.less';
import {RedoOutlined, CopyTwoTone, PlusOutlined} from '@ant-design/icons';
import CopyText from "@/components/CopyText/CopyText";
import useUUID from "rc-menu/es/hooks/useUUID";
import moment from "moment";

const {Meta} = Card;
/**
 * 主页
 * @constructor
 */
const UserCenter: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<API.UserVO>()
  const [formRef] = Form.useForm();
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewImage, setPreviewImage] = useState('');
  // ✅ Upload 组件配置（受控模式）
  const uploadProps: UploadProps = {
    maxCount: 1,
    name: 'userAvatar',
    action: '/upload.do',
    listType: 'picture-card',
    fileList, // ✅ 受控属性，控制显示的文件列表
    onChange(info) {
      setFileList(info.fileList); // ✅ 更新 fileList 状态
    },

  };

  const loadData = async () => {
    setLoading(true)
    const res = await getLoginUserUsingGet()
    try {
      if (res?.data) {
        setData(res.data)
      }
    } catch (e) {
      message.error('删除失败.' + e.message);
    } finally {
      setLoading(false)
    }
  };
  const refreshAccessKey = async () => {
    setLoading(true)
    const res = await refreshAccessKeyUsingPost();
    try {
      if (res?.data) {
        setData({
          ...data,
          accessKey: res?.data
        })
        message.success('签名更新成功')
      }
    } catch (e) {
      message.error('更新失败.' + e.message);
    } finally {
      setLoading(false)

    }
  }
  const updateClick = async (values) => {
    if (!data && !data?.id) {
      return
    }
    setLoading(true)
    const res = await updateUserUsingPost({
      id: data?.id,
      ...values
    })
    try {
      if (res?.data) {
        loadData()
        message.success('更新成功')
      }
    } catch (e) {
      message.error('更新失败.' + e.message);
    } finally {
      setLoading(false)
    }
  }
  useEffect(() => {
    loadData();
  }, []);

  useEffect(() => {
    if(data&&formRef){
      // ✅ 回显普通字段
      formRef.setFieldsValue({
        userName: data.userName,
        email: data.email, // ✅ Input 已正确绑定 name="email"
      });

      // ✅ 回显头像：构造 UploadFile 格式
      if (data.userAvatar) {
        setFileList([
          {
            uid: moment().toJSON(), // 唯一ID，可以是后端返回的文件ID
            name: 'avatar', // 文件名，可自定义
            status: 'done', // 必须为 'done' 才会显示图片
            url: data.userAvatar, // 👈 必须有：图片的访问链接，用于显示预览
          },
        ]);
      }
    }

  }, [data]);
  return (
    <PageContainer title={'个人中心'} loading={loading}>
      <Space direction="vertical" size="middle" style={{display: 'flex'}}>
        <Card title="个人设置">
          <Form
            labelCol={{span: 4}}
            wrapperCol={{span: 14}}
            layout="horizontal"
            style={{maxWidth: 600}}
            autoComplete="off"
            labelAlign={"left"}
            form={formRef}
            onFinish={updateClick}
          >
            <Form.Item
              name="userName"
              label="昵称"
              required={true}
              rules={[
                {
                  required: true,
                  message: "昵称不能为空"
                },
                {whitespace: true}]}>
              <Input allowClear={true}/>
            </Form.Item>
            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                {
                  type: 'email',
                  message: '请输入正确的邮箱格式！',
                },
                {whitespace: true}]}
              extra={
                <Alert
                  message="填写邮件信息，会开启告警功能对接口使用异常进行邮件告警！"
                  type="warning"
                  showIcon
                  style={{marginTop: 4}}
                />}
            >
              <Input allowClear={true} style={{marginBottom: 12}}/>

            </Form.Item>

            <Form.Item label="头像" valuePropName="fileList">
              <Upload {...uploadProps}>
                <button style={{border: 0, background: 'none'}} type="button">
                  <PlusOutlined/>
                </button>
              </Upload>
            </Form.Item>
            <Form.Item wrapperCol={{offset: 4, span: 16}}>
              <Button type="primary" htmlType="submit">
                修改
              </Button>
            </Form.Item>
          </Form>
        </Card>
        <Card title="签名(调用接口的凭证)"
              extra={<Button onClick={refreshAccessKey} icon={< RedoOutlined/>}>重新生成</Button>}>
          {data ? (
            <Descriptions column={1}>
              <Descriptions.Item label="accessKey">  {data?.accessKey} <CopyText text={data?.accessKey}/>
              </Descriptions.Item>
            </Descriptions>
          ) : (
            <>暂无凭证，请重新生成！！！</>
          )}

        </Card>
      </Space>
    </PageContainer>
  );
};

export default UserCenter;
